package com.nebula.upms.admin.support;

import com.nebula.upms.service.model.vo.UpmsUserVO;
import com.nebula.upms.service.support.constant.UpmsFinal;
import com.nebula.upms.service.support.datasource.UpmsDs;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Mtime on 2017/9/5.
 */
public class UpmsSession {
    /**
     * 获得当前登录用户
     * @param request
     * @return
     */
    public static UpmsUserVO currentUser(HttpServletRequest request){
        Map<String,Object> cookieMap=cookies2Map(request);

        String token= (String) cookieMap.get(UpmsFinal.UPMS_USERTOKEN);
        //System.out.println("1>>>>>>>>>>>"+token);
        if(null!=token){
            UpmsUserVO upmsUserVO= UpmsDs.instance().redis().get(UpmsFinal.KEYHEAD_UPMS_SESSION,token,UpmsUserVO.class);
            //(UpmsUserVO) RedisHelper.get(UpmsFinal.KEYHEAD_UPMS_SESSION+token,UpmsFinal.FIELD_UPMS_USERVO);
            return upmsUserVO;
        }else{
            return null;
        }

    }

    private static Map<String,Object> cookies2Map(HttpServletRequest request){
        Map<String,Object> cookieMap=new HashMap<String, Object>();
        Cookie[] cookies = request.getCookies();
        if(null!=cookies){
            for(Cookie c :cookies ){
                cookieMap.put(c.getName(), c.getValue());
            }
        }

        return cookieMap;
    }
}
